<!--授权信息-->
<template>
  <div class="authorization-infor">
    <el-form :inline="true" class="header">
      <div class="search-form">
        <el-form-item class="title">
          授权信息
        </el-form-item>
        <div>
          <div>
            <el-form-item>
              <el-input v-model="supplierName" placeholder="请输入供应商名称" clearable @keyup.enter.native="queryList('supplierName')">
                <el-button slot="append" class="search-icon" icon="icon-sousuo" @click="queryList('supplierName')"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-input v-model="ipAddress" placeholder="请输入IP" clearable @keyup.enter.native="queryList('ipAddress')">
                <el-button slot="append" class="search-icon" icon="icon-sousuo" @click="queryList('ipAddress')"></el-button>
              </el-input>
            </el-form-item>
          </div>
          <div>
            <el-form-item>
              <el-input v-model="accessId" placeholder="请输入Access ID" clearable @keyup.enter.native="queryList('accessId')">
                <el-button slot="append" class="search-icon" icon="icon-sousuo" @click="queryList('accessId')"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-input v-model="accessSecret" placeholder="请输入Access Secret" clearable @keyup.enter.native="queryList('accessSecret')">
                <el-button slot="append" class="search-icon" icon="icon-sousuo" @click="queryList('accessSecret')"></el-button>
              </el-input>
            </el-form-item>
          </div>
        </div>
        <!-- <el-button type="primary" class="search-btn" size="14" @click="handleAddOrder">搜索</el-button>
        <el-button class="button-container" size="14" @click="handleReset">重置</el-button> -->
      </div>
      <el-button type="primary" class="add-btn" size="14" @click="handleAddOrEditEmpower('add')">新增授权</el-button>
    </el-form>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }"
    >
      <el-table-column label="供应商">
        <template slot-scope="scope">
          {{ scope.row.supplierName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="IP">
        <template slot-scope="scope">
          {{ scope.row.ipAddress || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="Access ID">
        <template slot-scope="scope">
          {{ scope.row.accessId || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="Access Secret">
        <template slot-scope="scope">
          {{ scope.row.accessSecret || "-" }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="operate" @click="handleAddOrEditEmpower('edit', scope.row)">编辑</el-button>
          <el-button
            type="text"
            size="operate"
            @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
    <el-dialog
      :title="status === 'add' ? '新增授权' : '编辑授权'"
      :visible.sync="dialogVisible"
      width="596px"
      :before-close="handleClose"
      custom-class="white-list-dialog">
      <el-form
        ref="form"
        :model="addFormData"
        :rules="rules"
        width="596px"
        label-width="100px"
        label-position="right">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="addFormData.supplierName" :disabled="status !== 'add'" placeholder="请输入供应商的名称，1～30字符长度" maxlength="30" clearable></el-input>
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="addFormData.ipAddress" placeholder="请输入IP地址，多个之间以;间隔" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取消</el-button>
        <el-button type="primary" size="14" @click="onsubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getList, addAuthorization, updateAuthorization, deleteAuthorization } from '@/api/device-identity-auth/authorization'
export default {
  name: 'authorizationInfor',
  data() {
    return {
      tableData: [], // 列表数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      loading: true,
      dialogVisible: false,
      supplierName: '', // 供应商名称
      ipAddress: '',
      accessId: '',
      accessSecret: '',
      addFormData: {
        supplierName: '',
        ipAddress: ''
      },
      rules: {
        supplierName: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' },
          { min: 1, max: 30, message: '请输入供应商名称，0～30字符长度', trigger: 'blur' }
        ],
        ipAddress: [
          { required: true, message: '请输入IP地址', trigger: 'blur' },
          { validator: this.validateIp, trigger: 'blur' }
        ]
      },
      status: 'add' // 新增或编辑状态 add 新增  edit 编辑
    }
  },
  created() {
    this.queryList()
  },
  methods: {
    // 客户名称校验提示
    validateIp(rule, value, callback) {
      // 正确的IP地址的正则表达式
      const ipRegex = /^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})){3}$/
      const ips = value.split(';')
      const flag = ips.every(function(ip) {
        if (!ipRegex.test(ip)) {
          return false
        } else {
          return true
        }
      })
      if (!flag) {
        callback(new Error('请输入正确的ip地址'))
      } else {
        callback()
      }
    },
    /**
     * 列表数据
     * @param {*}
     */
    queryList(condition) {
      this.loading = true
      const params = {
        supplierName: condition === 'supplierName' ? this.supplierName : '',
        ipAddress: condition === 'ipAddress' ? this.ipAddress : '',
        accessId: condition === 'accessId' ? this.accessId : '',
        accessSecret: condition === 'accessSecret' ? this.accessSecret : '',
        size: this.pageSize,
        current: this.currentPage
      }
      getList(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 重置
    handleReset() {
      this.supplierName = ''
      this.ipAddress = ''
      this.accessId = ''
      this.accessSecret = ''
    },
    // 新增或者编辑授权
    handleAddOrEditEmpower(status, row) {
      this.addFormData.supplierName = status === 'edit' ? row.supplierName : ''
      this.addFormData.ipAddress = status === 'edit' ? row.ipAddress : ''
      this.status = status
      this.dialogVisible = true
    },
    // 删除
    handleDelete(id) {
      const params = {
        id: id
      }
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAuthorization(params).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.queryList()
        }).catch(err => {
          this.$message.error(err.message)
        })
      }).catch(err => {})
    },
    // 关闭授权弹窗
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
    },
    /**
     * 新增或编辑授权
     */
    onsubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            ...this.addFormData
          }
          let Authorization = ''
          if (this.status === 'add') {
            Authorization = addAuthorization
          } else {
            Authorization = updateAuthorization
          }
          Authorization(params).then(res => {
            this.dialogVisible = false
            this.$refs['form'].resetFields()
            if (this.status === 'add') {
              this.$message.success('新增成功')
            } else {
              this.$message.success('编辑成功')
            }
            this.queryList()
          }).catch(err => {
            this.$message.error(err.message)
          })
        } else {
          return false
        }
      })
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryList()
    }
  }
}
</script>
<style lang="scss" scoped>
.authorization-infor {

  .header {
    display: flex;
    justify-content: space-between;
  }
  .search-form {
    display: flex;

    ::v-deep .el-form-item {
      margin-right: 24px;
    }

    .title {
      margin-right: 34px;
      font-size: 18px;
      font-weight: 400;
      color: #252525;
    }

    .search-btn {
      margin-right: 24px;
    }
  }
}
</style>
